"""
@Project:study_platform
@File:jwt_token.py
@Author:韩晓雷
@Date:19:55
"""


import jwt
import datetime
from functools import wraps
from rest_framework.response import Response
from user.models import *


# jwt
class MyJwt:

    def __init__(self):
        # 初始化秘钥
        self.password = '123456789'

    # 生命周期token
    def encode_time(self, userinfo):
        payload = {
            # 当前时间点 + 时间周期
            "exp": int((datetime.datetime.now() + datetime.timedelta(seconds=30)).timestamp()),
            'data': userinfo
        }

        encoded_jwt = jwt.encode(payload, self.password, algorithm="HS256")

        return encoded_jwt

    # 生成token
    def encode(self, userinfo):
        encode_jwt = jwt.encode(userinfo, self.password, algorithm='HS256')
        return encode_jwt

    # 解密方法
    def decode(self, token):
        decode_jwt = jwt.decode(token, self.password, algorithms=['HS256'])
        return decode_jwt


# token 验证
def check_login(func):
    @wraps(func)
    def wrapper(self, request, *args, **kwargs):
        token = request.headers.get("token")

        if not token:
            return Response({"code": 400, "msg": "token不存在"})

        myjwt = MyJwt()

        try:
            user = myjwt.decode(token)
        except Exception as e:
            print(str(e))
            return Response({"code": 401, "msg": "token不合法"})

        try:
            user = UserModel.objects.get(id=user['id'])
            self._cuser = user

        except Exception as e:
            print("获取用户失败的原因", e)
            return Response({"code": 403, "msg": "用户不存在"})

        return func(self, request, *args, **kwargs)

    return wrapper







